package com.dikang.keer.product.service.impl;

import com.dikang.common.to.SkuReductionTo;
import com.dikang.common.to.SpuBoundsTo;
import com.dikang.common.utils.PageUtils;
import com.dikang.common.utils.Query;
import com.dikang.common.utils.R;
import com.dikang.keer.product.entity.*;
import com.dikang.keer.product.feign.CouponFeignService;
import com.dikang.keer.product.service.*;
import com.dikang.keer.product.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.dikang.keer.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }
    @Override
    @Transactional
    public void saveSpu( SpuSaveVo spuSaveVo) {
        // 1、保存spu基本信息， pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveSpuInfo(spuInfoEntity);
        // 2、保存spu的描述图片 pms_spu_info_desc
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        List<String> decript = spuSaveVo.getDecript();
        Long spuId = spuInfoEntity.getId();
        spuInfoDescEntity.setSpuId(spuId);
        spuInfoDescEntity.setDecript(String.join(",",decript));
        this.saveSpuInfoDesc(spuInfoDescEntity);
        // 3、保存图片集 pms_spu_images
            if (spuSaveVo.getImages()!=null&&spuSaveVo.getImages().size()>0){
                spuImagesService.saveSpuImages(spuId,spuSaveVo.getImages());
            }
        // 4、 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> attrValueEntityList = baseAttrs.stream().map(
                (item) -> {
                    ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
                    productAttrValueEntity.setAttrId(item.getAttrId());
                    productAttrValueEntity.setAttrName(attrService.getById(item.getAttrId()).getAttrName());
                    productAttrValueEntity.setAttrValue(item.getAttrValues());
                    productAttrValueEntity.setQuickShow(item.getShowDesc());
                    productAttrValueEntity.setSpuId(spuInfoEntity.getId());
                    return productAttrValueEntity;
                }
        ).collect(Collectors.toList());
        productAttrValueService.saveProductAttrValue(attrValueEntityList);
        // 5、 保存spu的积分信息keer_sms->sms_spu_bounds

        Bounds bounds = spuSaveVo.getBounds();
        if (bounds !=null){
            SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
            spuBoundsTo.setBuyBounds(bounds.getBuyBounds());
            spuBoundsTo.setGrowBounds(bounds.getGrowBounds());
            spuBoundsTo.setSpuId(spuId);
            R r = couponFeignService.saveSpuBounds(spuBoundsTo);
            if ( r.getCode()!=0){
                log.info("远程保存spu积分信息失败");
            }
        }
        // 获取默认图片
        // 6保存spu对应的所有sku信息
        List<Skus> skus = spuSaveVo.getSkus();
    skus.stream()
        .map(
            (sku) -> {
              SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
              BeanUtils.copyProperties(sku, skuInfoEntity);
              skuInfoEntity.setBrandId(spuSaveVo.getBrandId());
              skuInfoEntity.setCatalogId(spuSaveVo.getCatalogId());
              skuInfoEntity.setSaleCount(0L);
              List<Images> images = sku.getImages();

              skus.forEach(
                  item -> {
                    for (Images a : item.getImages()) {
                      if (a.getDefaultImg() == 1) {
                          String defaulImage = a.getImgUrl();
                        skuInfoEntity.setSkuDefaultImg(defaulImage);
                      }
                    }

                  });
              // 6.1保存sku的基本信息 pms_sku_info
                if (skuInfoEntity.getPrice().compareTo(new BigDecimal("0"))==1){
                    skuInfoService.saveSKuInfo(skuInfoEntity);
                }
              Long skuId = skuInfoEntity.getSkuId();
              // 6.2保存sku的图片信息 pms_sku_images
              List<SkuImagesEntity> skuImagesEntityList =
                  sku.getImages().stream()
                      .map(
                          (images1) -> {
                            SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                            skuImagesEntity.setSkuId(skuId);
                            skuImagesEntity.setImgUrl(images1.getImgUrl());
                            skuImagesEntity.setDefaultImg(images1.getDefaultImg());
                            return skuImagesEntity;
                          })
                      .filter(
                          (entity) -> {
                            return !StringUtils.isEmpty(entity.getImgUrl());
                          })
                      .collect(Collectors.toList());
              skuImagesService.saveBatch(skuImagesEntityList);
              // 6.3保存sku的销售属性信息 pms_sku_sale_attr_value
              List<Attr> attr = sku.getAttr();
              if (attr != null && attr.size() > 0) {
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities =
                    attr.stream()
                        .map(
                            (item) -> {
                              SkuSaleAttrValueEntity skuSaleAttrValueEntity =
                                  new SkuSaleAttrValueEntity();
                              BeanUtils.copyProperties(item, skuSaleAttrValueEntity);
                              skuSaleAttrValueEntity.setSkuId(skuId);
                              return skuSaleAttrValueEntity;
                            })
                        .collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
              }

              // 6.4 sku的优惠，满减信息 keer_sms->sms_sku_ladder\sms_sku_full_reduction
              SkuReductionTo skuReductionTo = new SkuReductionTo();
              BeanUtils.copyProperties(sku,skuReductionTo);
              skuReductionTo.setSkuId(skuId);
              if (skuReductionTo.getFullCount() > 0 && skuReductionTo.getFullPrice() != null
                  || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                R r = couponFeignService.saveSkuFullReduction(skuReductionTo);
                if (r.getCode() != 0) {
                  log.info("远程保存满减优惠失败");
                }
              }
              return skuInfoEntity;
            })
        .collect(Collectors.toList());
    }




    /**
     *   2、保存spu的描述图片 pms_spu_info_desc
     * @param spuInfoDescEntity
     */
    private void saveSpuInfoDesc(SpuInfoDescEntity spuInfoDescEntity) {
        spuInfoDescService.save(spuInfoDescEntity);
    }

    /**
     *  // 1、保存spu基本信息， pms_spu_info
     * @param spuInfoEntity
     */
    private void saveSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.save(spuInfoEntity);

    }


}